package com.hulk.dryad.web.oauth2.config;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hulk.dryad.common.constant.SecurityConstants;
import com.hulk.dryad.manage.security.component.DryadAuthExceptionEntryPoint;
import com.hulk.dryad.manage.tenant.TenantContextHolder;
import com.hulk.dryad.web.oauth2.base.component.DryadUserAuthenticationConverter;
import com.hulk.dryad.web.oauth2.base.component.DryadWebResponseExceptionTranslator;
import com.hulk.dryad.web.oauth2.base.service.DryadRedisTokenStore;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultAuthenticationKeyGenerator;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.UserAuthenticationConverter;

/**
 * @author hulk
 * @date 2019/6/22 认证服务器配置
 */

@Configuration
@RequiredArgsConstructor
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

	private final ClientDetailsService dryadClientDetailsServiceImpl;

	private final AuthenticationManager authenticationManagerBean;

	private final UserDetailsService dryadUserDetailsService;

	private final AuthorizationCodeServices authorizationCodeServices;

	private final DryadRedisTokenStore dryadRedisTokenStore;

	private final TokenEnhancer dryadTokenEnhancer;

	private final ObjectMapper objectMapper;

	@Override
	@SneakyThrows
	public void configure(ClientDetailsServiceConfigurer clients) {
		clients.withClientDetails(dryadClientDetailsServiceImpl);
	}


	@Override
	public void configure(AuthorizationServerSecurityConfigurer oauthServer) {
		oauthServer.allowFormAuthenticationForClients()
				.authenticationEntryPoint(new DryadAuthExceptionEntryPoint(objectMapper))
				.checkTokenAccess("isAuthenticated()");

	}

	@Override
	public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
		// 设置tokenStore 前缀相关
		String prefix = String.format(":%s%s", SecurityConstants.DRYAD_PREFIX, SecurityConstants.OAUTH_PREFIX);
		dryadRedisTokenStore.setPrefix(prefix);
		// 设置区分key 条件
		dryadRedisTokenStore.setAuthenticationKeyGenerator(new DefaultAuthenticationKeyGenerator() {
			@Override
			public String extractKey(OAuth2Authentication authentication) {
				return super.extractKey(authentication) + StrUtil.COLON + TenantContextHolder.getTenantId();
			}
		});
		endpoints.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST).tokenStore(dryadRedisTokenStore)
				.tokenEnhancer(dryadTokenEnhancer).userDetailsService(dryadUserDetailsService)
				.authorizationCodeServices(authorizationCodeServices).authenticationManager(authenticationManagerBean)
				.reuseRefreshTokens(false).pathMapping("/oauth/confirm_access", "/token/confirm_access")
				.exceptionTranslator(new DryadWebResponseExceptionTranslator());


		//TOKEN转换器扩展
		DefaultAccessTokenConverter accessTokenConverter = new DefaultAccessTokenConverter();
		UserAuthenticationConverter userTokenConverter = new DryadUserAuthenticationConverter();
		accessTokenConverter.setUserTokenConverter(userTokenConverter);
		endpoints.accessTokenConverter( accessTokenConverter );
	}
}
